package com.example.springboot.manager;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class EmailManager {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    private static Configuration configuration;

    @Resource
    public void setConfiguration(Configuration configuration) {
        EmailManager.configuration = configuration;
    }

    /**
     * 发送邮件 使用HTML文本渲染
     * @param to 收件人
     * @param subject 主题
     */
    public void sendEmailRenderHTML(String to, String subject) {
        // 设置邮件内容
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //获取验证码 存入redis
            int randomCode = (int) ((Math.random() * 9 + 1) * 100000);
//            redisUtil.set(Constant.CUSTOMER_EMAIL + email, randomCode, 1800);
            //邮箱发送内容组成
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject(subject);
            helper.setText(buildContent(randomCode + ""), true);
            helper.setTo(to);
            helper.setFrom(from);
            mailSender.send(message);
        } catch (Exception e) {
//            throw new CustomerException(messageSourceUtil.getMessage(I18nConstant.SYSTEM_ERROR), "500");
        }
    }

    /**
     * 发送简单邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendEmailSimple(String to, String subject, String content) {
            // 创建SimpleMailMessage对象
            SimpleMailMessage message = new SimpleMailMessage();
            // 设置邮件发送人
            message.setFrom(from);
            // 设置邮件接收人
            message.setTo(to);
            // 设置邮件主题
            message.setSubject(subject);
            // 设置邮件内容
            message.setText(content);
            // 设置发送邮件
            mailSender.send(message);
    }

    /**
     * 读取邮件模板
     * 替换模板中的信息
     *
     * @param title 内容
     * @return
     */
    public String buildContent(String title) {
        try {
            Template temp = configuration.getTemplate("email.ftl");
            Map<String, String> map = new HashMap<>();
            map.put("code", title);
            StringWriter stringWriter = new StringWriter();
            temp.process(map, stringWriter);
            return stringWriter.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
